package com.toivan.mt.utils;

import android.content.Context;
import android.content.res.AssetManager;
import android.os.Handler;
import android.text.TextUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.toivan.mt.model.MtAtmosphere;
import com.toivan.mt.model.MtAtmosphereManager;
import com.toivan.mt.model.MtDynamicSticker;
import com.toivan.mt.model.MtDynamicStickerManager;
import com.toivan.mt.model.MtExpression;
import com.toivan.mt.model.MtExpressionManager;
import com.toivan.mt.model.MtGreenScreen;
import com.toivan.mt.model.MtGreenScreenManager;
import com.toivan.mt.model.MtMask;
import com.toivan.mt.model.MtMaskManager;
import com.toivan.mt.model.MtPortrait;
import com.toivan.mt.model.MtPortraitManager;
import com.toivan.sdk.MtSDK;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MtJsonParser {

    private static MtJsonParser instance;
    private final Handler mHandler;
    //地址
    private final String PATH_STICKER = MtSDK.get().getStickerPath() + File.separator + "stickers.json";
    private final String PATH_EXPRESSION = MtSDK.get().getExpressionPath() + File.separator + "expressions.json";
    private final String PATH_MASK = MtSDK.get().getMaskPath() + File.separator + "masks.json";
    private final String PATH_ATMOSPHERE = MtSDK.get().getAtmospherePath() + File.separator + "atmospheres.json";
    private final String PATH_GREEN_SCREEN = MtSDK.get().getGreenScreenPath() + File.separator + "greenscreens.json";
    private final String PATH_PORTRAITS = MtSDK.get().getPortraitPath() + File.separator + "portraits.json";

    private MtDynamicStickerManager dynamicStickerManager;
    private MtExpressionManager expressionManager;
    private MtMaskManager maskManager;
    private MtAtmosphereManager atmosphereManager;
    private MtPortraitManager portraitManager;
    private MtGreenScreenManager greenScreenManager;

    ExecutorService cachedThreadPool = Executors.newCachedThreadPool();


    private MtJsonParser() {
        mHandler = new Handler();
    }


    public static MtJsonParser getInstance() {
        if (instance == null) {
            synchronized (MtJsonParser.class) {
                if (instance == null) {
                    instance = new MtJsonParser();
                }
            }
        }
        return instance;
    }

    public List<MtDynamicSticker> getAllDynamicStickers() {
        if (dynamicStickerManager != null) {
            return dynamicStickerManager.getStickers();
        }
        return null;
    }


    public List<MtExpression> getAllExpressions() {
        if (expressionManager != null) {
            return expressionManager.getExpressions();
        }
        return null;
    }


    public List<MtPortrait> getAllPortrait() {
        if (portraitManager != null) {
            return portraitManager.getPortraits();
        } else {
            return null;
        }
    }


    public List<MtGreenScreen> getAllGreenScreen() {
        if (greenScreenManager != null) {
            return greenScreenManager.getGreenscreens();
        } else {
            return null;
        }
    }


    public List<MtMask> getAllMasks() {
        if (maskManager != null) {
            return maskManager.getMasks();
        }
        return null;
    }


    public List<MtAtmosphere> getAllAtmospheres() {
        if (atmosphereManager != null) {
            return atmosphereManager.getAtmospheres();
        }
        return null;
    }


    public MtDynamicStickerManager getDynamicStickerManager() {
        if (dynamicStickerManager != null) {
            return dynamicStickerManager;
        }
        return null;
    }


    public MtPortraitManager getPortraitManager() {
        if (portraitManager != null) {
            return portraitManager;
        }
        return null;
    }


    public MtGreenScreenManager getGreenScreenManager() {
        if (greenScreenManager != null) {
            return greenScreenManager;
        }
        return null;
    }


    public MtExpressionManager getExpressionManager() {
        if (expressionManager != null) {
            return expressionManager;
        }
        return null;
    }


    public MtMaskManager getMaskManager() {
        if (maskManager != null) {
            return maskManager;
        }
        return null;
    }

    public MtAtmosphereManager getAtmosphereManager() {
        if (atmosphereManager != null) {
            return atmosphereManager;
        }
        return null;
    }

    public void getDynamicStickers(final MtCallback<List<MtDynamicSticker>> callback) {
        cachedThreadPool.execute(new Runnable() {
            @Override public void run() {
                String result = getFileString(PATH_STICKER);
                if (!TextUtils.isEmpty(result)) {
                    dynamicStickerManager = new Gson().fromJson(result, new TypeToken<MtDynamicStickerManager>() {
                    }.getType());
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (callback != null) {
                                callback.callback(dynamicStickerManager.getStickers());
                            }
                        }
                    });
                }
            }
        });
    }

    public void getExpressions(final MtCallback<List<MtExpression>> callback) {
        cachedThreadPool.execute(new Runnable() {
            @Override public void run() {
                String result = getFileString(PATH_EXPRESSION);
                if (!TextUtils.isEmpty(result)) {
                    expressionManager = new Gson().fromJson(result, new TypeToken<MtExpressionManager>() {
                    }.getType());
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (callback != null) {
                                callback.callback(expressionManager.getExpressions());
                            }
                        }
                    });
                }
            }
        });
    }

    //从配置文件中获取所有的抠图配置
    public void getPortraits(final MtCallback<List<MtPortrait>> callback) {
        cachedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                String result = getFileString(PATH_PORTRAITS);
                if (!TextUtils.isEmpty(result)) {
                    portraitManager = new Gson().fromJson(result, new TypeToken<MtPortraitManager>() {
                    }.getType());
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (callback != null) {
                                callback.callback(portraitManager.getPortraits());
                            }
                        }
                    });
                }
            }
        });
    }

    /**
     * 获取配置文件下的所有绿幕
     */
    public void getGreenScreens(final MtCallback<List<MtGreenScreen>> callback) {
        cachedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                String result = getFileString(PATH_GREEN_SCREEN);
                if (!TextUtils.isEmpty(result)) {
                    greenScreenManager = new Gson().fromJson(result, new TypeToken<MtGreenScreenManager>() {
                    }.getType());
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (callback != null) {
                                callback.callback(greenScreenManager.getGreenscreens());
                            }
                        }
                    });
                }
            }
        });
    }

    public void getMasks(final MtCallback<List<MtMask>> callback) {
        cachedThreadPool.execute(new Runnable() {
            @Override public void run() {
                String result = getFileString(PATH_MASK);
                if (!TextUtils.isEmpty(result)) {
                    maskManager = new Gson().fromJson(result, new TypeToken<MtMaskManager>() {
                    }.getType());
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (callback != null) {
                                callback.callback(maskManager.getMasks());
                            }
                        }
                    });
                }
            }
        });
    }

    public void getAtmospheres(final MtCallback<List<MtAtmosphere>> callback) {
        cachedThreadPool.execute(new Runnable() {
            @Override public void run() {
                String result = getFileString(PATH_ATMOSPHERE);
                if (!TextUtils.isEmpty(result)) {
                    atmosphereManager = new Gson().fromJson(result, new TypeToken<MtAtmosphereManager>() {
                    }.getType());
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (callback != null) {
                                callback.callback(atmosphereManager.getAtmospheres());
                            }
                        }
                    });
                }
            }
        });
    }

    public void stickerDownload(final String content) {
        cachedThreadPool.execute(new Runnable() {
            @Override public void run() {
                modifyFile(content, PATH_STICKER);
            }
        });
    }

    public void expressionDownload(final String content) {
        cachedThreadPool.execute(new Runnable() {
            @Override public void run() {
                modifyFile(content, PATH_EXPRESSION);
            }
        });
    }

    public void maskDownload(final String content) {
        cachedThreadPool.execute(new Runnable() {
            @Override public void run() {
                modifyFile(content, PATH_MASK);
            }
        });
    }

    public void portraitsDownload(final String content) {
        cachedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                modifyFile(content, PATH_PORTRAITS);
            }
        });
    }

    public void greenScreenDownload(final String content) {
        cachedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                modifyFile(content, PATH_GREEN_SCREEN);
            }
        });
    }

    public void atmosphereDownload(final String content) {
        cachedThreadPool.execute(new Runnable() {
            @Override public void run() {
                modifyFile(content, PATH_ATMOSPHERE);
            }
        });
    }

    private String getFileString(String filePath) {
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();
        try {
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            br = new BufferedReader(new InputStreamReader(fis));
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
//            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }

    private void modifyFile(String content, String filePath) {
        try {
            FileWriter fileWriter = new FileWriter(filePath, false);
            BufferedWriter writer = new BufferedWriter(fileWriter);
            writer.append(content);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //版本更新，删除内部存储中的文件，使用assets文件重新创建
    public void resetFile(final Context context) {
        cachedThreadPool.execute(new Runnable() {
            @Override public void run() {
                String newSticker = getJsonString(context, "toivan/sticker/stickers.json");
                modifyFile(newSticker, PATH_STICKER);

                String newExpression = getJsonString(context, "toivan/expression/expressions.json");
                modifyFile(newExpression, PATH_EXPRESSION);

                String newMask = getJsonString(context, "toivan/mask/masks.json");
                modifyFile(newMask, PATH_MASK);

                String newAtmosphere = getJsonString(context, "toivan/atmosphere/atmospheres.json");
                modifyFile(newAtmosphere, PATH_ATMOSPHERE);

                String newPortraits = getJsonString(context, "toivan/portrait/portraits.json");
                modifyFile(newPortraits, PATH_PORTRAITS);

                String newGreenScreen = getJsonString(context, "toivan/greenscreen/greenscreens.json");
                modifyFile(newGreenScreen, PATH_GREEN_SCREEN);
            }
        });
    }

    private String getJsonString(Context context, String fileName) {
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();
        try {
            AssetManager manager = context.getAssets();
            br = new BufferedReader(new InputStreamReader(manager.open(fileName)));
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }



}


